# -*- coding:utf-8 -*-
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
import sys, time
import base64


class prpcrypt():
    def __init__(self):
        # key值（密码）
        self.key = '******************'
        # vi偏移量
        self.iv = '****************'
        self.mode = AES.MODE_CBC
        self.BS = AES.block_size
        self.pad = lambda s: s + (self.BS - len(s) % self.BS) * chr(self.BS - len(s) % self.BS)
        self.unpad = lambda s: s[0:-ord(s[-1])]

    # 加密
    def encrypt(self, text):
        text = self.pad(text)
        cryptor = AES.new(self.key, self.mode, self.iv)
        # 目前AES-128 足够目前使用(CBC加密)
        ciphertext = cryptor.encrypt(text)
        # base64加密
        return base64.b64encode(bytes(ciphertext))

    # 解密
    def decrypt(self, text):
        # base64解密
        text = base64.b64decode(text)
        cryptor = AES.new(self.key, self.mode, self.iv)
        # CBC解密
        plain_text = cryptor.decrypt(text)
        # 去掉补足的空格用strip() 去掉
        return self.unpad(plain_text.rstrip('\0'))


if __name__ == '__main__':
    pc = prpcrypt()  # 初始化密钥 和 iv
    # text='access&a494fcbc-9aa1-4718-bd7d-a90d01211d97&0&2&'
    text = 'access&a494fcbc-9aa1-4718-bd7d-a90d01211d97&0&1&'
    # text='access&a494fcbc-9aa1-4718-bd7d-a90d01211d97&1&1&'
    # text='access&a494fcbc-9aa1-4718-bd7d-a90d01211d97&1&2&'
    # text='update&a494fcbc-9aa1-4718-bd7d-a90d01211d97&0&2&'
    # text='update&a494fcbc-9aa1-4718-bd7d-a90d01211d98&0&2&'
    # text='logout&'
    e = pc.encrypt(text + str(int(time.time() / 10)))  # 加密
    d = pc.decrypt(e)  # 解密
    print("加密:", e)
    # print
    # "解密:", d
    # print
    # "长度:", len(d)
